package com.config.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.config.entity.Equipment;
import com.config.entity.LineConfig;
import com.config.service.EquipmentService;
import com.config.service.LineConfigService;

/** 
 * @author Hexrui
 * @date 2016年5月26日 下午5:53:14 
 */

@Controller
@RequestMapping("/equip")
public class EquipController {
	
	@Resource(name="equipmentService")
	private EquipmentService equipmentService;
	@Resource(name="lineConfigService")
	private LineConfigService lineService;
	
	@RequestMapping("/findByLine")
	public @ResponseBody Model findByLine(Model model,
			@RequestParam(value="lineId",required=false,defaultValue="0")int lineId,
			@RequestParam(value = "page", required = false, defaultValue="0") int start,
			@RequestParam(value = "rows", required = false, defaultValue="10") int limit){
		if(lineId==0){
			//获取第一条生产线
			LineConfig line=lineService.findFirstLine();
			lineId=line.getId();
		}
		model.addAttribute("total", equipmentService.countByLine(lineId));
		model.addAttribute("rows", equipmentService.findByLine(lineId,start, limit));
		return model;
	}
	
	@RequestMapping("/save")
	public Model save(Model model ,Equipment entity,@RequestParam("file") MultipartFile myfile,
			HttpServletRequest request){
		if(!myfile.isEmpty()){  
            String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
            String ext = FilenameUtils.getExtension(myfile.getOriginalFilename()).toLowerCase();
            String newName = new Date().getTime()+"."+ext;
            try {
            	FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, newName));
            } catch (IOException e) {
            	e.printStackTrace();
            }  
            entity.setEquPhoto(newName);
        }
		List<Equipment> list=equipmentService.listByLine(entity.getLineId());
		Equipment equ=equipmentService.getByEquNo(entity.getEquNo());
		if(list.size()>20){
			model.addAttribute("success",false);
			model.addAttribute("msg","一条生产线下最多只20个设备");
		}else{
			if(equ!=null){
				model.addAttribute("success",false);
				model.addAttribute("msg","设备编号有重复，请重新编辑");
			}else{
				equipmentService.save(entity);
				model.addAttribute("success",true);
				model.addAttribute("msg","保存成功");
			}
		}
		return model;
	}
	
	@RequestMapping("/load")
	public Model load(Model model ,int id){
		Equipment entity=equipmentService.getEquipment(id);
		model.addAttribute("data",entity);
		model.addAttribute("success",true);
		model.addAttribute("msg","加载成功");
		return model;
	}
	
	@RequestMapping("/update")
	public Model upload(Model model,Equipment entity){
		equipmentService.update(entity);
		model.addAttribute("success",true);
		model.addAttribute("msg","修改成功");
		return model;
	}
	
	@RequestMapping("/updatePhoto")
	public Model updatePhoto(Model model ,int id,@RequestParam("file") MultipartFile myfile,
			HttpServletRequest request){
		Equipment entity=equipmentService.getEquipment(id);
		if(!myfile.isEmpty()){  
            String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
            String ext = FilenameUtils.getExtension(myfile.getOriginalFilename()).toLowerCase();
            String newName = new Date().getTime()+"."+ext;
            try {
            	FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, newName));
            } catch (IOException e) {
            	e.printStackTrace();
            }
//            System.out.println(realPath);
            entity.setEquPhoto(newName);
            equipmentService.update(entity);
            model.addAttribute("success",true);
            model.addAttribute("msg","修改成功");
        }else{
        	model.addAttribute("success",false);
            model.addAttribute("msg","图片未更改");
        }
		return model;
	}
	
	@RequestMapping("/delete")
	public Model delete(Model model ,int id,HttpServletRequest request){
		Equipment entity=equipmentService.getEquipment(id);
		if(entity.getIsCollect().equals("Y")){
			model.addAttribute("success",false);
			model.addAttribute("msg","该设备已采集数据，不能删除");
		}else{
			String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
			File f = new File(realPath+"\\"+entity.getEquPhoto()); // 输入要删除的文件位置
			if(f.exists()){
				f.delete();
			}
			equipmentService.delete(id);
			model.addAttribute("success",true);
			model.addAttribute("msg","删除成功");
		}
		return model;
	}
	/**
	 * 获取设备下拉框
	 * @param model
	 * @return
	 */
	@RequestMapping("/equComboBox")
	public Map<String,Object> equComboBox(HttpServletResponse response){
		Map<String,Object> map=new HashMap<String,Object>();
		response.setHeader("Access-Control-Allow-Origin", "*");
		map.put("equComboBox", equipmentService.getAllEquipment());
	    return map;
	}
}
